const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})

exports.main = async (event) => {
	try {
		const { OPENID } = cloud.getWXContext()

		const DB = cloud.database()

		const updateParam = { ...event }
		delete updateParam._id
		delete updateParam.userInfo

		await DB.collection('gn_space').doc(event._id).update({
			data: updateParam,
		})

		const space = await DB.collection('gn_space').doc(event._id).get()

		let user = await DB.collection('gn_user').doc(OPENID).get()

		const userSpaceIndexBefoeUpdate = user.data.space
		const index = userSpaceIndexBefoeUpdate.findIndex((space) => space._id === event._id)

		if (index > -1) {
			userSpaceIndexBefoeUpdate[index].name = event.name
			await DB.collection('gn_user')
				.doc(OPENID)
				.update({
					data: {
						space: userSpaceIndexBefoeUpdate,
					},
				})
			user = await DB.collection('gn_user').doc(OPENID).get()
		}

		return {
			data: {
				space: space.data,
				user: user.data,
			},
			code: 0,
			msg: '更新成功',
		}
	} catch (err) {
		throw err
	}
}
